<template>
  <div>
    <el-dialog
      title="信息修改"
      :visible.sync="updateDialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <div>
        <el-form
          ref="updateForm"
          :rules="updateFormRules"
          :model="updateForm"
          label-width="180px"
        >
          <el-row>
            <el-col :span="10">
              <el-form-item label="项目名称">
                <el-input
                  disabled
                  v-model="updateForm.extractItem"
                  placeholder="请输入项目名称"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="建设地址">
                <el-input
                  v-model="updateForm.extractAddress"
                  placeholder="请输入建设地址"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="建设周期">
                <el-input
                  v-model="updateForm.extractPeriod"
                  placeholder="请输入建设周期"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="工程费用（万元）">
                <el-input
                  v-model="updateForm.extractPrice"
                  placeholder="请输入工程费用"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="工程概况">
                <el-input
                  type="textarea"
                  v-model="updateForm.projectOverview"
                  placeholder="请输入工程概况"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="中介机构服务费（万元）">
                <el-input
                  v-model="updateForm.maxPrice"
                  placeholder="请输入中介机构服务费"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="抽取要求">
                <el-input
                  v-model="updateForm.extractBanReason"
                  placeholder="请输入抽取要求"
                ></el-input>
              </el-form-item>
            </el-col>
                        <el-col :span="10">
              <el-form-item label="经办人">
                <el-input
                  v-model="updateForm.extractCharge"
                  placeholder="请输入经办人"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="业务类型">
                <el-input
                  v-model="updateForm.extractBusinessType"
                  placeholder="请输入业务类型"
                ></el-input>
              </el-form-item>
            </el-col>
              <el-col :span="10">
              <el-form-item label="抽取单位数">
                <el-input
                  v-model="updateForm.extractNumber"
                  placeholder="请输入抽取单位数"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="是否需要驻场服务">
                <el-radio-group v-model="updateForm.extractResident">
                  <el-radio label="0">是</el-radio>
                  <el-radio label="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="驻场服务人数(至少)">
                <el-input
                  v-model="updateForm.extractResidentNumber"
                  placeholder="请输入驻场服务人数"
                  type="number"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="10">
              <el-form-item label="驻场要求">
                <el-input
                  v-model="updateForm.extractStationRequire"
                  placeholder="请输入驻场要求"
                ></el-input>
              </el-form-item>
            </el-col>
              <el-col :span="10">
              <el-form-item label="抽取库">
                <el-select
                  v-model="updateForm.randomUnittypeId"
                  placeholder="请选择单位库"
                  style="width: 100%"
                  disabled
                >
                  <el-option
                    v-for="item in ExtractLibraryOptions"
                    :key="item.unittypeId"
                    :label="item.unittypeName"
                    :value="item.unittypeId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <simpleTable :simpleTableData="simpleTableData"></simpleTable>

          <el-form-item label="中标确认">
            <el-select
              clearable
              v-model="form.randomId"
              placeholder="请选择中标单位"
            >
              <el-option
                v-for="(item, index) in pullDownCompanyInfo"
                :key="index"
                :label="item.randomUnitName"
                :value="item.randomId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-row v-if="updateForm.extractApproveStatus === '8'">
            <el-col :span="12">
              <el-form-item
                label="项目开始时间"
                label-width="183px"
                prop="projectStartTime"
              >
                <el-date-picker
                  :clearable="false"
                  v-model="updateForm.projectStartTime"
                  type="date"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="项目结束时间"
                label-width="183px"
                prop="projectEndTime"
              >
                <el-date-picker
                  :clearable="false"
                  v-model="updateForm.projectEndTime"
                  type="date"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                >
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="结算金额（万元）" prop="settleAmount">
                <el-input v-model="updateForm.settleAmount" type="number" class="calc-cash"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否正常结束" prop="isNormalEnd">
                <el-radio-group v-model="updateForm.isNormalEnd">              
                  <el-radio :label="0">是</el-radio>
                  <el-radio :label="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="updateForm.extractApproveStatus === '8'">
            <el-col :span="24">
              <el-form-item label="评分表" prop="markSheet">
                <el-upload
                  class="remain"
                  ref="uploadFile"
                  :accept="acceptType"
                  :limit="1"
                  :on-exceed="onExceed"
                  action=""
                  :http-request="uploadFile"
                  :show-file-list="false"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                  <div slot="tip" class="el-upload__tip">
                    请上传bmp，gif，jpg，jpeg，png格式文件，且大小不超过10MB
                  </div>
                </el-upload>
                <div class="upload-wrap">
                  <div
                    class="show-img-wrap"
                    v-for="(item, index) in imgUrl"
                    :key="index"
                  >
                    <el-image
                      class="show-img"
                      style="width: 100px; height: 100px"
                      :src="item"
                      @click="handleImageView"
                    />
                    <img
                      @click="delImg(1, index)"
                      class="icon-wrap"
                      src="./../../../../../assets/images/del.png"
                      alt=""
                    />
                  </div>
                </div>
              </el-form-item>
              <el-form-item
                class="deduction-wrap"
                label="违规扣分"
                prop="deductScore"
              >
                <ul class="remain" style="margin: 0">
                  <li v-for="(item, index) in deductScore" :key="index">
                    <div class="deduction-title">{{ item.ruleName }}</div>
                    <div>
                      <el-radio v-model="item.whetherDeduct" label="0"
                        >是</el-radio
                      >
                      <el-radio v-model="item.whetherDeduct" label="1"
                        >否</el-radio
                      >
                    </div>
                  </li>
                </ul>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row v-if="updateForm.extractApproveStatus === '8'">
            <el-col :span="24">
              <el-form-item label="扣分原因" prop="deductCause">
                <el-input
                  type="textarea"
                  v-model="updateForm.deductCause"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="updateDialogConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 报价弹窗   -->
    <el-dialog title="修改" :visible.sync="priceDialog" width="30%">
      <div class="company-item">
        <label>单位名称：</label>
        <p>{{ priceForm.randomUnitName }}</p>
      </div>
      <!-- <div class="company-item">
          <label>状态：</label>
          <p>{{ handleRandomBan(priceForm.randomBan) }}</p>
        </div> -->
      <div class="company-item">
        <label>金额（元）：</label>
        <input
          type="number"
          placeholder="请输入金额"
          v-model="priceForm.bidamount"
        />
      </div>
      <div class="must">*报价填写说明：按实际投标报价填写，单位为（元）。折扣比率报价时，用小数表示（如：65%填写为0.65）。</div>
      <!-- <div class="company-item">
          <label>中标文本上传：</label>
          <el-upload
            class="remain"
            ref="uploadFile"
            :accept="acceptType"
            :limit="3"
            :on-exceed="onExceed"
            action=""
            :http-request="uploadPriceFile"
            :show-file-list="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">请上传bmp，gif，jpg，jpeg，png格式文件，且大小不超过10MB</div>
          </el-upload>
        </div> -->
      <div class="price-upload-wrap">
        <div
          class="price-show-img-wrap"
          v-for="(item, index) in priceImgUrl"
          :key="index"
        >
          <el-image
            class="price-show-img"
            style="width: 100px; height: 100px"
            :src="item"
          />
          <img
            @click="delImg(2, index)"
            class="icon-wrap"
            src="./../../../../../assets/images/del.png"
            alt=""
          />
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="priceDialog = false">取 消</el-button>
        <el-button type="primary" @click="priceDialogConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog :visible.sync="imageView" width="40%" class="img-view">
      <img :src="imgUrl[0]" alt="">
    </el-dialog>
  </div>
</template>

<script>
import simpleTable from "@/common/operation/simpleTable";
import service from "@/views/components/utils/request";
import {
  approvalViewConfirm,
  shortPoints,
  winningUnitConfirm,
} from "@/api/unit/extract";
export default {
  name: "updateDialog",
  components: {
    simpleTable,
  },
  props: [
    "updateDialogVisible",
    "unitTypeOptions",
    "currentRow",
    "tableCompany",
    "companyInfo",
    "deductScore",
  ],
  data() {
    return {
      form: {
        randomId: "",
      },
      beginTime: "",
      updateForm: {},
      updateFormRules: {
        projectEndTime: [
          { required: true, message: "请输入项目结束时间", trigger: "blur" },
        ],
        projectStartTime: [
          { required: true, message: "请输入项目开始时间", trigger: "blur" },
        ],
        // deductReason: [
        //   { required: true, message: '请输入扣分原因', trigger: 'blur'  }
        // ],
      },
      ExtractLibraryOptions: [],
      simpleTableData: {
        title: ["单位名称", "状态", "报价金额（元）", "抽取时间", "操作"], //使用方传， 组件第一个li里面的div的循环数据
        list: [],
      },
      pullDownCompanyInfo: [],
      fileList: [],
      radioList: [],
      priceDialog: false,
      priceForm: {},
      acceptType: "bmp,gif,jpg,jpeg,png", // 可接受的上传文件的类型
      imgUrl: [], //  显示的图片路径
      priceImgUrl: [],
      imageView: false,
      srcList: []
    };
  },
  methods: {
    handleClose() {
      this.simpleTableData.list = [];
      this.$refs.uploadFile?this.$refs.uploadFile.clearFiles():null;
      this.$emit("handleUpdateClose");
    },
    // 文件个数超出限制
    onExceed(files, fileList) {
      this.$message.error("最多只能上传一个文件");
    },

    // 上传文件
    async uploadFile(eleFile) {
      this.imgUrl = [];
      const file = eleFile.file;
      let fileType = file.name.split(".");
      fileType = fileType[fileType.length - 1];
      if (!this.acceptType.includes(fileType)) {
        return this.$message.error("文件类型不正确");
      }
      if (file.size > 10 * 1024 * 1024) {
        return this.$message.error("文件大小不能超过10MB");
      }
      const fd = new FormData();
      fd.append("file", file);
      try {
        const res = await service.post("/common/upload", fd, {
          headers: { "content-type": "multipart/form-data" },
        });
        if (res.code === 200) {
          this.imgUrl.push(res.url);
          this.$message.success("上传成功");
        } else {
          this.$message.error(res.msg);
        }
      } catch (e) {
        this.$message.error(e);
      }
    },
    // 上传报价上传文件
    async uploadPriceFile(eleFile) {
      const file = eleFile.file;
      let fileType = file.name.split(".");
      fileType = fileType[fileType.length - 1];
      if (!this.acceptType.includes(fileType)) {
        return this.$message.error("文件类型不正确");
      }
      if (file.size > 10 * 1024 * 1024) {
        return this.$message.error("文件大小不能超过10MB");
      }
      const fd = new FormData();
      fd.append("file", file);
      try {
        const res = await service.post("/common/upload", fd, {
          headers: { "content-type": "multipart/form-data" },
        });
        if (res.code === 200) {
          this.priceImgUrl.push(res.url);
          this.$message.success("上传成功");
        } else {
          this.$message.error(res.msg);
        }
      } catch (e) {
        this.$message.error(e);
      }
    },
    // 删除文件
    delImg(ident, index) {
      this.$confirm("确定删除该文件吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (ident === 1) {
            this.imgUrl.splice(index, 1);
          } else {
            this.priceImgUrl.splice(index, 1);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 处理公司状态
    handleRandomBan(val) {
      switch (val) {
        case "0":
          return "正常";
        case "1":
          return "排除";
        case "2":
          return "中签";
        case "3":
          return "中标";
        case "4":
          return "未中标";
        case "5":
          return "废除报价";
      }
    },
    // 报价弹窗确定
    async priceDialogConfirm() {
      const params = {};
      params.randomId = this.priceForm.randomId;
      params.randomUnitName = this.priceForm.randomUnitName;
      params.randomBan = this.priceForm.randomBan;
      params.bidamount = this.priceForm.bidamount;
      params.randomQuoteTable = this.priceImgUrl.join(",");
      const res = await approvalViewConfirm(params);
      if (res.code === 200) {
        this.$message.success(res.msg);
        this.priceDialog = false;
        this.$set(
          this.simpleTableData.list[this.priceForm.index],
          2,
          this.priceForm.bidamount
        );
      } else {
        this.$message.error(res.msg);
      }
    },
    // 中标确认确定
    updateDialogConfirm() {
      if (!this.form.randomId) {
        return this.$message.error("请选择中标单位");
      }
      this.$refs.updateForm.validate((valid) => {
        if (!valid) {
          return;
        }
        // if(this.imgUrl.length === 0){
        //   return this.$message.error('请上传评分表')
        // }
        if (this.updateForm.extractApproveStatus === "8") {
          this.$confirm("确认提交吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              Promise.all([this.winningfirm(), this.saveInfo()]).then(() => {
                this.$message.success("操作成功");
                this.handleClose();
              });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消提交",
              });
            });
        } else {
          this.$confirm("确认提交吗?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              this.winningfirm();
              this.handleClose();
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消提交",
              });
            });
        }
      });
    },
    // 中标单位确认1
    async winningfirm() {
      const params = {};
      params.randomId = this.form.randomId;
      params.extractId = this.currentRow.extractId;
      try {
        await winningUnitConfirm(params);
      } catch (e) {
        this.$message.error(e);
      }
    },
    // 违规扣分
    async saveInfo() {
      const obj = {
        ...this.updateForm,
        extractId: this.currentRow.extractId,
        extractItem: this.currentRow.extractItem,
        randomId: this.form.randomId,
        // deductReason: this.updateForm.deductReason,
        // projectStartTime: this.updateForm.projectStartTime,
        // projectEndTime: this.updateForm.projectEndTime,
        deductList: this.deductScore,
        extractApproveStatus: "8",
        // settleAmount: this.updateForm.settleAmount,
        // isNormalEnd: this.updateForm.isNormalEnd,
        markSheet: this.imgUrl.toString()
      };
      // 违规扣分
      try {
        const query = JSON.stringify(obj);
        await shortPoints(query);
      } catch (e) {
        this.$message.error(e);
      }
    },
    handleImageView() {
      this.imageView = true;
    }
  },
  watch: {
    unitTypeOptions: {
      immediate: true,
      handler(val) {
        this.ExtractLibraryOptions = val;
      },
    },
    currentRow: {
      handler(val) {
        this.updateForm = val;
        this.beginTime = val.projectStartTime;
        this.imgUrl = val.markSheet === null ? [] : val.markSheet.split(",");
      },
    },
    tableCompany: {
      immediate: true,
      handler(val) {
        val.forEach((item) => {
          this.simpleTableData.list.push([
            item.randomUnitName,
            this.handleRandomBan(item.randomBan),
            item.bidamount === null ? "" : item.bidamount,
            item.createTime,
            {
              //对象
              handleTile: "报价",
              callBack: (currentRow, index) => {
                this.priceForm = item;
                this.priceImgUrl =
                  item.randomUrl === null ? [] : item.randomUrl.split(",");
                this.priceDialog = true;
                this.priceForm.index = index;
              },
            },
          ]);
        });
      },
    },
    companyInfo: {
      immediate: true,
      handler(val) {
        this.pullDownCompanyInfo = val;
        val.map((item) => {
          if (item.randomBan === "3") {
            this.form.randomId = item.randomId;
          }
        });
      },
    },
  },
};
</script>

<style lang="scss" scoped>
ul {
  list-style: none;
  margin: 0;
  padding: 0;
}
li {
  display: flex;
  > div {
    flex: 1;
  }
}
::v-deep .el-textarea__inner {
  height: 90px !important;
  resize: none;
}
::v-deep .el-dialog__body {
  max-height: 800px !important;
  overflow: auto !important;
}
::v-deep ul[data-v-b0cfc8a2] {
  margin: 0 45px 20px;
}
::v-deep .el-dialog:not(.is-fullscreen) {
  margin-top: 1% !important;
}
.company-item {
  display: flex;
  align-items: baseline;
  padding: 10px 0;
  width: 100%;
  > label {
    width: 130px;
    text-align: right;
  }
}
p {
  padding: 0;
  margin: 0;
}
input {
  outline: none;
}
.upload-wrap {
  display: flex;
  .show-img-wrap {
    padding-top: 10px;
    position: relative;
    .show-img {
      margin-right: 10px;
      margin-bottom: 8px;
    }
    .icon-wrap {
      position: absolute;
      top: 8px;
      right: 9px;
      width: 20px;
      height: 20px;
      cursor: pointer;
    }
  }
}
.price-upload-wrap {
  padding: 10px 30px 0px;
  display: flex;
  flex-wrap: wrap;
  .price-show-img-wrap {
    width: 25%;
    position: relative;
    .icon-wrap {
      position: absolute;
      top: -6px;
      right: 13px;
      width: 18px;
      height: 18px;
    }
  }
}
.calc-cash {
  width: 217px;
  input {
    width: 100%;
  }
}
.img-view {
  text-align: center;
  img {
    width: 100%;
  }
}
.must {
  color: rgb(255,0,0);
}
</style>
